import {
  getProfileAPI,
  getUserInfoAPI,
  loginAPI,
  sendCodeAPI,
  updatePhotoAPI,
  updateProfileAPI,
} from "@/api/user";
import { saveAuth } from "@/utils/storage";
import { Toast } from "antd-mobile";
import { AppDispatch } from "..";
import { IProfile } from "@/store/reducer/user";

export const sendCodeAction = (mobile: string) => {
  return async () => {
    await sendCodeAPI(mobile);
  };
};

export const loginAction = (mobile: string, code: string) => {
  return async () => {
    const res = await loginAPI(mobile, code);
    Toast.show({ content: "登录成功", icon: "success" });
    saveAuth(res.data);
  };
};

export const getUserInfoAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserInfoAPI();
    dispatch({ type: "user/saveUserInfo", payload: res.data });
  };
};

export const getProfileAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getProfileAPI();
    dispatch({ type: "user/saveProfile", payload: res.data });
  };
};

export const updatePhotoAction = (formData: FormData) => {
  return async (dispatch: AppDispatch) => {
    await updatePhotoAPI(formData);
  };
};

export const updateProfileAction = (profile: Partial<IProfile>) => {
  return async () => {
    await updateProfileAPI(profile);
  };
};
